package org.vison.wonfu.framework.soa.discovery;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.vison.wonfu.framework.commons.Constants;
import org.vison.wonfu.framework.commons.utils.IpUtils;
import org.vison.wonfu.framework.config.utils.MultiLevelConfigProvider;

@Component
public class AutoServiceRegistration implements ApplicationListener<ApplicationEvent> {


    private static final Logger logger = LoggerFactory.getLogger(AutoServiceRegistration.class);

    private boolean registered = false;

    private  ServiceRegistryDiscovery serviceRegistry;

    private  ServiceInstance localServiceInstance;

    private MultiLevelConfigProvider defaultMultiLevelConfigProvider;

    private ServerProperties serverProperties;



    @Autowired
    public AutoServiceRegistration(ServiceRegistryDiscovery serviceRegistry, MultiLevelConfigProvider defaultMultiLevelConfigProvider,
                                   ServerProperties serverProperties) {
        this.serviceRegistry = serviceRegistry;
        this.serverProperties = serverProperties;
        this.defaultMultiLevelConfigProvider = defaultMultiLevelConfigProvider;
        String exposeIp = getExposeIp();
        ServiceInstance localServiceInstance = new ServiceInstance(defaultMultiLevelConfigProvider.getString(Constants.APP_ID),exposeIp,getHttpPort());
        this.localServiceInstance = localServiceInstance;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        // 容器刷新完成后注册服务（对应 Spring 启动完成）
        Boolean providerEnable = defaultMultiLevelConfigProvider.getBoolean(Constants.CONFIG_KEY_SOA_PROVIDER_ENABLE,false);
        if(event instanceof ContextRefreshedEvent && !registered){
            if(providerEnable){
                register();
            }
        }
        // 容器关闭前注销服务（对应 Spring 关闭）
        if(event instanceof ContextClosedEvent && registered) {
            if(providerEnable){
                deregister();
            }
        }
    }

    private void register() {
        logger.info("Registering service: {}", localServiceInstance);
        serviceRegistry.register(localServiceInstance);
        registered = true;
    }

    private void deregister() {
        serviceRegistry.deregister(localServiceInstance);
        registered = false;
    }


    private int getHttpPort() {
        // 获取配置的端口（若未配置，默认8080）
        return serverProperties.getPort() != null ? serverProperties.getPort():8080;
    }


    /**
     * 1. 优先注册 Pod IP（默认推荐）
     * 场景：服务仅在 K8s 集群内部被调用（如微服务间通信）；
     * 2. 注册 Node IP + NodePort（适合跨集群访问）
     * 场景：服务需要被 K8s 集群外的非 K8s 服务调用，且无 Ingress 时；
     * 获取准备向注册中心注册IP地址
     * 1. 优先获取pod ip，从环境变量
     * 2. 读取配置文件ip
     * 3. 获取本机非回环的IPv4地址
     * @return
     */
    private String getExposeIp(){
        String podIp = System.getenv("POD_IP");
        if (podIp != null && !podIp.isEmpty()) {
            return podIp;
        }
        String exposeIp = defaultMultiLevelConfigProvider.getString(Constants.CONFIG_KEY_EXPOSE_IP);
        if (exposeIp != null && !exposeIp.isEmpty()) {
            return exposeIp;
        }
        // 若未配置，则获取本机非回环的IPv4地址
        return IpUtils.getLocalHostIp();

    }


}
